package com.bangdream.michelia.tool.retrofithttp;

import android.util.Log;

import com.alibaba.fastjson.JSON;
import com.bangdream.michelia.application.AppCurrentUser;
import com.bangdream.michelia.application.MainApplication;
import com.bangdream.michelia.entity.BaseEntity;
import com.bangdream.michelia.entity.UserInfoBean;
import com.bangdream.michelia.utils.SPUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.Observable;

import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.ObservableSource;
import io.reactivex.ObservableTransformer;
import io.reactivex.Single;
import io.reactivex.SingleOnSubscribe;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import okhttp3.MediaType;
import okhttp3.RequestBody;


public class TokenManagerDef extends TokenManager<Object> {
    public static final String TOKENERROR="";
    public static final String SUCCESS="success";
    public static final String FAIL="fail";
    private static final String TAG = "token_log";
    public static boolean TokenError;
    public static String token;

    private volatile static TokenManagerDef tokenManagerDef;

    public static synchronized TokenManagerDef newInstance() {
        if (tokenManagerDef == null)
            tokenManagerDef = new TokenManagerDef();
        return tokenManagerDef;
    }

    @Override
    void createTokenObservableAndSend() {
        Map<String, String> map = new HashMap<>();
        map.put("accountName", (String) SPUtils.get(MainApplication.getContext(), "userName", ""));
        map.put("loginType", "1");
        map.put("password", (String) SPUtils.get(MainApplication.getContext(), "pwd", "123456"));
        map.put("type", "2");
        String jsonString = JSON.toJSONString(map);
        RequestBody requestBody = RequestBody.create(MediaType.parse("application/json; charset=utf-8"),
                jsonString);
        Log.d(TAG, "请求Token...");
        RetroFactory.getInstance().actionLogin(requestBody).doOnNext(new Consumer<BaseEntity<UserInfoBean>>() {
            @Override
            public void accept(BaseEntity<UserInfoBean> beanBaseEntity) throws Exception {

                if (beanBaseEntity.getData() != null && beanBaseEntity.getData().getToken() != null){
                    Log.d(TAG, "存储Token=" + beanBaseEntity.getData().getToken());
                    AppCurrentUser.getInstance().setToken(beanBaseEntity.getData().getToken());
                    sendSuccess(SUCCESS);
                }else {
                    throw new Exception();
                }
            }
        }).doOnError(throwable -> {
            Log.d(TAG, "获取token失败");
            sendSuccess(FAIL);
        }).subscribeOn(Schedulers.io())
          .onErrorResumeNext(io.reactivex.Observable.never())
        .subscribe();
    }

    @Override
    boolean intercept(Throwable throwable) {
        return throwable instanceof TokenEX;
    }

    @Override
    boolean isOK(Object object) {
        return SUCCESS.equals(object);
    }



    public static Function<BaseEntity,BaseEntity> checkedToken() {
        return baseEntity -> {
            if (baseEntity.getMessage() != null) {
                if (baseEntity.getMessage().contains("ZUUL_ERROR_00002")) {
                    Log.d(TAG, "token 错误");
                    throw new TokenEX();
                }
            }
            return baseEntity;
        };
    }


    public static class TokenEX extends Exception{

    }
}
